<template>
  <div class="reminder-list-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>跟进提醒管理</h2>
          <el-button
            type="primary"
            @click="createReminderDialog = true"
          >
            + 手动创建提醒
          </el-button>
        </div>
      </template>

      <!-- 筛选栏 -->
      <el-row
        :gutter="16"
        style="margin-bottom: 16px"
      >
        <el-col :span="6">
          <el-select
            v-model="filters.status"
            placeholder="筛选状态"
            clearable
            @change="fetchReminders"
          >
            <el-option
              label="待处理"
              value="pending"
            />
            <el-option
              label="已发送"
              value="sent"
            />
            <el-option
              label="已完成"
              value="completed"
            />
            <el-option
              label="已取消"
              value="cancelled"
            />
          </el-select>
        </el-col>
      </el-row>

      <!-- 提醒列表 -->
      <el-table
        v-loading="loading"
        :data="reminders"
        stripe
        style="width: 100%"
      >
        <el-table-column
          label="客户"
          width="180"
        >
          <template #default="{ row }">
            <div>{{ row.lead_name }}</div>
            <div style="color: #909399; font-size: 12px">
              {{ row.lead_phone }}
            </div>
          </template>
        </el-table-column>

        <el-table-column
          label="提醒类型"
          width="100"
        >
          <template #default="{ row }">
            <el-tag :type="row.reminder_type === 'auto' ? 'success' : 'info'">
              {{ row.reminder_type === 'auto' ? '自动' : '手动' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          label="触发原因"
          prop="trigger_reason"
          min-width="200"
        />

        <el-table-column
          label="提醒时间"
          width="180"
        >
          <template #default="{ row }">
            {{ formatDateTime(row.reminder_time) }}
          </template>
        </el-table-column>

        <el-table-column
          label="状态"
          width="100"
        >
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          label="备注"
          prop="notes"
          min-width="150"
          show-overflow-tooltip
        />

        <el-table-column
          label="操作"
          width="200"
          fixed="right"
        >
          <template #default="{ row }">
            <el-button
              v-if="row.status === 'pending' || row.status === 'sent'"
              size="small"
              type="primary"
              @click="markComplete(row.id)"
            >
              标记完成
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="deleteReminder(row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        style="margin-top: 16px; justify-content: flex-end"
        @current-change="fetchReminders"
        @size-change="fetchReminders"
      />
    </el-card>

    <!-- 手动创建提醒对话框 -->
    <el-dialog
      v-model="createReminderDialog"
      title="手动创建提醒"
      width="600px"
    >
      <el-form
        :model="newReminder"
        label-width="120px"
      >
        <el-form-item
          label="客户ID"
          required
        >
          <el-input-number
            v-model="newReminder.lead_id"
            :min="1"
            placeholder="输入客户ID"
            style="width: 100%"
          />
          <div style="color: #909399; font-size: 12px; margin-top: 4px">
            提示：可在客户列表页面查看客户ID
          </div>
        </el-form-item>
        <el-form-item
          label="提醒时间"
          required
        >
          <el-date-picker
            v-model="newReminder.reminder_time"
            type="datetime"
            placeholder="选择提醒时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="触发原因">
          <el-input
            v-model="newReminder.trigger_reason"
            placeholder="如：客户要求回访"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="newReminder.notes"
            type="textarea"
            :rows="3"
            placeholder="输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createReminderDialog = false">
          取消
        </el-button>
        <el-button
          type="primary"
          :loading="creating"
          @click="submitCreateReminder"
        >
          创建
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { reminderApi } from '@/api'
import type { ReminderWithLead } from '@/api/modules/reminder'

const reminders = ref<ReminderWithLead[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(50)
const loading = ref(false)
const filters = ref({ status: '' })
const createReminderDialog = ref(false)
const creating = ref(false)
const newReminder = ref({
  lead_id: null as number | null,
  reminder_time: null as Date | null,
  trigger_reason: '',
  notes: ''
})

// 加载提醒列表
async function fetchReminders() {
  loading.value = true
  try {
    const response = await reminderApi.getList({
      status: filters.value.status || undefined,
      page: page.value,
      page_size: pageSize.value
    })
    reminders.value = response.data.items
    total.value = response.data.total
  } catch (error) {
    ElMessage.error('加载失败')
  } finally {
    loading.value = false
  }
}

// 标记完成
async function markComplete(reminderId: number) {
  try {
    await reminderApi.markComplete(reminderId)
    ElMessage.success('已标记完成')
    fetchReminders()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 删除提醒
async function deleteReminder(reminderId: number) {
  try {
    await ElMessageBox.confirm('确定删除此提醒？', '警告', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
    await reminderApi.delete(reminderId)
    ElMessage.success('删除成功')
    fetchReminders()
  } catch (error) {
    // 用户取消或删除失败
  }
}

// 提交创建提醒
async function submitCreateReminder() {
  if (!newReminder.value.lead_id || !newReminder.value.reminder_time) {
    ElMessage.warning('请填写必填字段')
    return
  }

  creating.value = true
  try {
    await reminderApi.create({
      lead_id: newReminder.value.lead_id,
      reminder_type: 'manual',
      trigger_reason: newReminder.value.trigger_reason || '手动创建',
      reminder_time: newReminder.value.reminder_time.toISOString(),
      assigned_to: 1, // 当前用户ID（实际应从store获取）
      notes: newReminder.value.notes
    })
    ElMessage.success('创建成功')
    createReminderDialog.value = false
    // 重置表单
    newReminder.value = {
      lead_id: null,
      reminder_time: null,
      trigger_reason: '',
      notes: ''
    }
    fetchReminders()
  } catch (error) {
    ElMessage.error('创建失败')
  } finally {
    creating.value = false
  }
}

// 格式化日期时间
function formatDateTime(dateStr: string) {
  const date = new Date(dateStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 获取状态类型
function getStatusType(status: string): 'success' | 'warning' | 'info' | 'danger' {
  const map: Record<string, 'success' | 'warning' | 'info' | 'danger'> = {
    pending: 'warning',
    sent: 'info',
    completed: 'success',
    cancelled: 'info'
  }
  return map[status] || 'info'
}

// 获取状态标签
function getStatusLabel(status: string) {
  const map: Record<string, string> = {
    pending: '待处理',
    sent: '已发送',
    completed: '已完成',
    cancelled: '已取消'
  }
  return map[status] || status
}

onMounted(() => {
  fetchReminders()
})
</script>

<style scoped>
.reminder-list-page {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
}
</style>
